package com.czxy.service;

import com.alibaba.fastjson.JSON;
import com.czxy.dao.SkuCommentMapper;
import com.czxy.dao.SkuMapper;
import com.czxy.dao.SpuMapper;
import com.czxy.pojo.ESData;
import com.czxy.pojo.Sku;
import com.czxy.pojo.Spu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 查询与ElasticSearch对接的数据
 * @author Liuyunqin 17674029449@163.com
 * @date 2018/12/25 8:11
 */
@Service
@Transactional
public class ESDataService {

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private SkuCommentMapper skuCommentMapper;

    public List<ESData> findAll(){
        //1. 准备容器存放数据
        List<ESData> esDataList = new ArrayList();
        //2.查询所有的sku数据
        List<Sku> skus = this.skuMapper.selectAll();

        //3. 遍历
        for (Sku sku : skus) {
            //***准备ES数据***
            ESData esData = new ESData();
            //3.1 skuid
            esData.setId(sku.getId());
            //3.2 logo
            esData.setLogo(sku.getImages());
            //3.3 sku_name
            esData.setSku_name(sku.getSku_name());

            //3.4 查询对应的spu
            Spu spu = this.spuMapper.findSpuBySpuId(sku.getSpu_id());

            //3.5 all = sku_name + 品牌  + 三级分类
            String all = sku.getSku_name() + "  " +spu.getBrand().getBrand_name()+"  " + spu.getCat3().getCatName() ;
            esData.setAll(all);

            //3.6  on_sale_time(销售时间)
            Date on_sale_time = spu.getOn_sale_time();
            long time = on_sale_time.getTime();
            esData.setOn_sale_time(time);

            //3.7 brand_id
            esData.setBrand_id(spu.getBrand_id());
            //3.8 cat3_id
            esData.setCat3_id(spu.getCat3_id());
            //3.9 规格列表 : {"机身颜色":"白色","内存":"3GB","机身存储":"16GB"}
            //需要类型转换。
            Map map = JSON.parseObject(sku.getSpec_list_code(), Map.class);
            esData.setSpecs(map);

            //3.10 价格
            esData.setPrice(sku.getPrice());
            //3.11 spu_name
            esData.setSku_name(spu.getSpu_name());
            //3.12 库存量
            esData.setStock(sku.getStock());
            //3.13 商品详情
            esData.setDescription(spu.getDescription());
            //3.14 包装
            esData.setPackages(spu.getPackages());
            //3.15 售后
            esData.setAftersale(spu.getAftersale());
            //3.16 评价数
            Integer countBySkuId = this.skuCommentMapper.findCountBySkuId(sku.getId());
            esData.setComment_count(countBySkuId);
            //3.17 销量
            Integer sellCountBySkuId = skuMapper.findSellCountBySkuId(sku.getId());
            esData.setSeller_count(sellCountBySkuId);

            //4.将data放入容器中
            esDataList.add(esData);
        }
        return esDataList;
    }


}
